package com.wjy.Data_Structure.graph;

import com.wjy.Data_Structure.linearlist.common.Iterator;
import com.wjy.Data_Structure.linearlist.common.LinkedList;
import com.wjy.Data_Structure.linearlist.listslinkimpl.LinkedListDLNode;

public class UndirectedGraph extends AbstractGraph {

	public UndirectedGraph() {
		super(Graph.UndirectedGraph);
	}

	@Override
	public void remove(Vertex v) {
		while (v.getDeg() > 0) {
			Edge e = (Edge) v.getAdjacentEdges().first().getData();
			remove(e);
		}
		vertexs.remove(v.getVexPosition());
	}

	@Override
	public void remove(Edge e) {
		edges.remove(e.getEdgePosition());
		Vertex u = e.getFirstVex();
		Vertex v = e.getSecondVex();
		u.getAdjacentEdges().remove(e.getEdgeFirstPosition());
		v.getAdjacentEdges().remove(e.getEdgeSecondPosition());
	}

	@Override
	public Edge edgeFromTo(Vertex u, Vertex v) {
		LinkedList adjEdge = u.getAdjacentEdges();
		Iterator it = adjEdge.elements();
		Edge e = null;
		for (it.first(); !it.isDone(); it.next()) {
			e = (Edge) it.currentItem();
			if (e.getSecondVex() == v || e.getFirstVex() == v)
				return e;
		}
		return null;
	}

	@Override
	public Iterator adjVertexs(Vertex u) {
		LinkedList adjVex = new LinkedListDLNode();
		LinkedList adjEdge = u.getAdjacentEdges();
		Iterator it = adjEdge.elements();
		Edge e = null;
		Vertex i = null, j = null;
		for (it.first(); !it.isDone(); it.next()) {
			e = (Edge) it.currentItem();
			i = e.getFirstVex();
			j = e.getSecondVex();
			if (i == u)
				adjVex.insertLast(j);
			else
				adjVex.insertLast(i);
		}
		return adjVex.elements();
	}

}
